package com.shadowlight.hero_story.cmdHandler;

import com.alibaba.fastjson.JSONObject;
import com.shadowlight.hero_story.Broadcaster;
import com.shadowlight.hero_story.config.AllConfig;
import com.shadowlight.hero_story.mq.MQProducer;
import com.shadowlight.hero_story.mq.VictorMsg;
import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.pojo.User;
import com.shadowlight.hero_story.pojo.UserRepository;
import com.shadowlight.hero_story.rank.RankService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description todo
 * @Author cz
 * @Date 2022/3/7
 */
@Slf4j
public class UserAttackCmdHandler implements ICmdHandler<GameMsgProtocol.UserAttkCmd> {


    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.UserAttkCmd msg) {
        //返回被攻击结果
        int targetUserId = msg.getTargetUserId();
        Integer currentUserId = (Integer) channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).get();
        if (currentUserId == null) return;
        GameMsgProtocol.UserAttkResult.Builder attackResultBuilder = GameMsgProtocol.UserAttkResult.newBuilder();
        attackResultBuilder.setAttkUserId(currentUserId);
        attackResultBuilder.setTargetUserId(targetUserId);
        Broadcaster.broadcast(attackResultBuilder.build());
        //被攻击用户减血结果
        GameMsgProtocol.UserSubtractHpResult.Builder userSubHpResultBuilder = GameMsgProtocol.UserSubtractHpResult.newBuilder();
        userSubHpResultBuilder.setTargetUserId(targetUserId);
        userSubHpResultBuilder.setSubtractHp(10); //暂时直接定义为扣十滴血
        Broadcaster.broadcast(userSubHpResultBuilder.build());
        //用户血量低于0则发送死亡指令
        //用户死掉以后发送死亡指令同时删除用户，但是不删除通信信道
        User targetUser = UserRepository.getInstance().getUserById(targetUserId);
        log.info(JSONObject.toJSONString(targetUser));
        if (targetUser != null) {
            if (targetUser.isDied()) {
                GameMsgProtocol.UserDieResult.Builder dieResultBuilder = GameMsgProtocol.UserDieResult.newBuilder();
                dieResultBuilder.setTargetUserId(targetUserId);
                Broadcaster.broadcast(dieResultBuilder.build());
            } else {
                targetUser.setCurrentHeap(targetUser.getCurrentHeap() - 10);
                if (targetUser.getCurrentHeap() <= 0) {
                    targetUser.setDied(true);
                    UserRepository.getInstance().save(targetUser);

                    if (AllConfig.ROCKETMQ_ENABLE) {
                        VictorMsg victorMsg = new VictorMsg(currentUserId, targetUserId);
                        MQProducer.sendMsg("Victor", victorMsg);
                    } else {
                        //如果未启动mq则直接修改redis的击杀数
                        RankService.getInstance().refreshRank(currentUserId, targetUserId);
                    }
                }
            }
        }
    }
}
